$(function() {
	// init date tables
	var accountTable = $("#account_list").dataTable({
		"dom": '<"top"i>rt<"bottom"fp><"clear">',
		"deferRender": true,
		"processing" : true, 
	    "serverSide": true,
		"ajax": {
			url: base_url + "/accountinfo/pageList",
			type:"post",
	        data : function ( d ) {
	        	var obj = {};
	        	obj.accountName = $('#accountName').val();
	        	obj.companyName = $('#companyName').val();
	        	obj.start = d.start;
	        	obj.length = d.length;
                return obj;
            }
	    },
	    "searching": false,
	    "ordering": false,
	    //"scrollX": true,	// X轴滚动条，取消自适应
	    "columns": [
	                { "data": 'ta_id', "bSortable": false, "visible" : false},
	                { "data": 'tc_id', "bSortable": false, "visible" : false},
	                { "data": 'ta_nickname', "visible" : true,"width":'10%'},
	                { "data": 'ta_username', "visible" : true,"width":'10%'},
	                { 
	                	"data": 'ta_createdate', 
	                	"visible" : true, 
	                	"width":'10%',
	                	"render": function ( data, type, row ) {
	                		return data?moment(new Date(data)).format("YYYY-MM-DD"):"";
	                	}
	                },
	                { 
	                	"data": 'ta_freezedate', 
	                	"visible" : true, 
	                	"width":'10%',
	                	"render": function ( data, type, row ) {
	                		return data?moment(new Date(data)).format("YYYY-MM-DD"):"";
	                	}
	                },
	                { 
	                	"data": 'ta_lastlogintime', 
	                	"visible" : true, 
	                	"width":'15%',
	                	"render": function ( data, type, row ) {
	                		return data?moment(new Date(data)).format("YYYY-MM-DD HH:mm:ss"):"";
	                	}
	                },
	                { "data": 'ta_lastloginip', "visible" : true,"width":'10%'},
	                { "data": 'ta_logincount', "visible" : true,"width":'10%'},
	                { "data": 'tc_name', "visible" : true,"width":'10%'},
	                {
						"data": '操作' ,
						"width":'15%',
	                	"render": function ( data, type, row ) {
	                		return function(){
								var html = '<p id="'+ row.ta_id +'" '+
									' nickName="'+ row.ta_nickname +'" '+
									' freezetime="'+ row.ta_freezedate +'" '+
									' company="'+ row.tc_id +'" '+
									'>'+
									'<button class="btn btn-warning btn-xs update" type="button">编辑</button>  '+
									'<button class="btn btn-warning btn-xs updatePassword" type="button">修改密码</button>  '+
									'<button class="btn btn-danger btn-xs delete" type="job_del" type="button">删除</button>  '+
									'</p>';

	                			return html;
							};
	                	}
	                }
	            ],
		"language" : {
			"sProcessing" : "处理中...",
			"sLengthMenu" : "每页 _MENU_ 条记录",
			"sZeroRecords" : "没有匹配结果",
			"sInfo" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页，_TOTAL_ 条记录 )",
			"sInfoEmpty" : "无记录",
			"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
			"sInfoPostFix" : "",
			"sSearch" : "搜索:",
			"sUrl" : "",
			"sEmptyTable" : "表中数据为空",
			"sLoadingRecords" : "载入中...",
			"sInfoThousands" : ",",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "上页",
				"sNext" : "下页",
				"sLast" : "末页"
			},
			"oAria" : {
				"sSortAscending" : ": 以升序排列此列",
				"sSortDescending" : ": 以降序排列此列"
			}
		}
	});
	
	// 搜索按钮
	$('#searchBtn').on('click', function(){
		accountTable.fnDraw();
	});
	
	// job operate
	$("#account_list").on('click', '.delete',function() {
		var	typeName = "删除";
		var	url = base_url + "/accountinfo/delete";
		needFresh = true;
		
		var id = $(this).parent('p').attr("id");
		
		ComConfirm.show("确认" + typeName + "?", function(){
			$.ajax({
				type : 'POST',
				url : url,
				data : {
					"id" : id
				},
				dataType : "json",
				success : function(data){
					if (data.code == 200) {
						ComAlert.show(1, typeName + "成功", function(){
							if (needFresh) {
								window.location.href = base_url + "/accountinfo.action";
							}
						});
					} else {
						ComAlert.show(1, typeName + "失败");
					}
				},
			});
		});
	});
	
	// jquery.validate 自定义校验 “英文字母开头，只含有英文字母、数字和下划线”
	jQuery.validator.addMethod("myValid01", function(value, element) {
		var length = value.length;
		var valid = /^[a-zA-Z][a-zA-Z0-9_]*$/;
		return this.optional(element) || valid.test(value);
	}, "只支持英文字母开头，只含有英文字母、数字和下划线");
	
	// 新增
	$(".add").click(function(){
		$('#addModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var addModalValidate = $("#addModal .form").validate({
		errorElement : 'span',  
        errorClass : 'help-block',
        focusInvalid : true,  
        rules : {
        	nickname : {
        		required : true
        	},
        	username : {
        		required : true,
        		myValid01: true
        	},
        	password1 : {
				required : true,
				myValid01: true
			},
			password2 : {
				required : true,
				myValid01: true,
				equalTo: "#password1"
			}
        }, 
        messages : {  
        	username : {
            	required :"请输入账户名."
            },
            password1 : {
            	required :"请输入密码."
            },
            password2 : {
				required : "请再次输入密码.",
				equalTo : "两次输入密码不匹配."
			},
        },
		highlight : function(element) {  
            $(element).closest('.form-group').addClass('has-error');  
        },
        success : function(label) {  
            label.closest('.form-group').removeClass('has-error');  
            label.addClass("valid");
        },
        errorPlacement : function(error, element) {  
            element.parent('div').append(error);  
        },
        submitHandler : function(form) {
        	$.post(base_url + "/accountinfo/add",  $("#addModal .form").serialize(), function(data, status) {
    			if (data.code == "200") {
					$('#addModal').modal('hide');
						ComAlert.show(1, "新增账户成功", function(){
							//accountTable.fnDraw();
							//window.location.reload();
							window.location.href = base_url + "/accountinfo.action";
						});
    			} else {
    				if (data.msg) {
    					ComAlert.show(2, data.msg);
    				} else {
    					ComAlert.show(2, "新增失败");
    				}
    			}
    		});
		}
	});
	$("#addModal").on('hide.bs.modal', function () {
		$("#addModal .form")[0].reset();
		addModalValidate.resetForm();
		$("#addModal .form .form-group").removeClass("has-error");
	});

	/*$('#filterTime').daterangepicker({
	    "startDate": "05/03/2017",
	    "endDate": "05/09/2017"
	}, function(start, end, label) {
	  console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
	});*/
	
	$('#filterTime').daterangepicker({
        //autoApply:false,
		startDate:'2020-1-1 00:00:00',
        singleDatePicker:true,
        showDropdowns:true,        // 是否显示年月选择条件
		//timePicker: true, 			// 是否显示小时和分钟选择条件
		//timePickerIncrement: 10, 	// 时间的增量，单位为分钟
        //timePicker24Hour : true,
        opens : 'left', //日期选择框的弹出位置
		/*ranges: {
			'最近1小时': [moment().subtract(1, 'hours'), moment()],
			'今日': [moment().startOf('day'), moment().endOf('day')],
			'昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
			'最近7日': [moment().subtract(6, 'days'), moment()],
			'最近30日': [moment().subtract(29, 'days'), moment()],
			'本月': [moment().startOf('month'), moment().endOf('month')],
			'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
		},*/
        locale : {
            format: 'YYYY-MM-DD HH:mm:ss',
            separator : ' - ',
        	customRangeLabel : '自定义',
            applyLabel : '确定',
            cancelLabel : '取消',
            fromLabel : '起始时间',
            toLabel : '结束时间',
            daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
            monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
            firstDay : 1,
            startDate: moment().startOf('day'),
            endDate: moment().endOf('day')
        }
	});
	$('#filterTime1').daterangepicker({
		//autoApply:false,
		startDate:'2020-1-1 00:00:00',
		singleDatePicker:true,
		showDropdowns:true,        // 是否显示年月选择条件
		//timePicker: true, 			// 是否显示小时和分钟选择条件
		//timePickerIncrement: 10, 	// 时间的增量，单位为分钟
		//timePicker24Hour : true,
		opens : 'left', //日期选择框的弹出位置
		/*ranges: {
			'最近1小时': [moment().subtract(1, 'hours'), moment()],
			'今日': [moment().startOf('day'), moment().endOf('day')],
			'昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
			'最近7日': [moment().subtract(6, 'days'), moment()],
			'最近30日': [moment().subtract(29, 'days'), moment()],
			'本月': [moment().startOf('month'), moment().endOf('month')],
			'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
		},*/
		locale : {
			format: 'YYYY-MM-DD HH:mm:ss',
			separator : ' - ',
			customRangeLabel : '自定义',
			applyLabel : '确定',
			cancelLabel : '取消',
			fromLabel : '起始时间',
			toLabel : '结束时间',
			daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
			monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
			firstDay : 1,
			startDate: moment().startOf('day'),
			endDate: moment().endOf('day')
		}
	});
	
	
	
	// 更新
	$("#account_list").on('click', '.update',function() {
		// base data
		/*$("#updateModal .form input[name='id']").val($(this).parent('p').attr("id"));
		$('#updateModal .form select[name=jobGroup] option[value='+ $(this).parent('p').attr("jobGroup") +']').prop('selected', true);
		$("#updateModal .form input[name='jobDesc']").val($(this).parent('p').attr("jobDesc"));
		$("#updateModal .form input[name='jobCron']").val($(this).parent('p').attr("jobCron"));
		$("#updateModal .form input[name='author']").val($(this).parent('p').attr("author"));
		$("#updateModal .form input[name='alarmEmail']").val($(this).parent('p').attr("alarmEmail"));
		$('#updateModal .form select[name=executorRouteStrategy] option[value='+ $(this).parent('p').attr("executorRouteStrategy") +']').prop('selected', true);
		$("#updateModal .form input[name='executorHandler']").val($(this).parent('p').attr("executorHandler"));
		$("#updateModal .form input[name='executorParam']").val($(this).parent('p').attr("executorParam"));
        $("#updateModal .form input[name='childJobKey']").val($(this).parent('p').attr("childJobKey"));*/

		$("#updateModal .form input[name='id']").val($(this).parent().attr("id"));
		$("#updateModal .form input[name='nickname']").val($(this).parent().attr("nickname"));
		$("#updateModal .form input[name='freezetime']").data('daterangepicker').setStartDate(moment(new Date(parseInt($(this).parent().attr("freezetime")))).format("YYYY-MM-DD HH:mm:ss"));
		$("#updateModal .form select[name='company'] option[value="+$(this).parent('p').attr("company")+"]").prop('selected',true);
		// show
		$('#updateModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var updateModalValidate = $("#updateModal .form").validate({
		errorElement : 'span',  
        errorClass : 'help-block',
        focusInvalid : true,

		rules : {
			nickname : {
        		required : true
        	}
		},
		messages : {
			nickname : {
				required :"请输入账户名."
			}
		},
		highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');  
        },
        success : function(label) {  
            label.closest('.form-group').removeClass('has-error');  
            label.remove();  
        },
        errorPlacement : function(error, element) {  
            element.parent('div').append(error);  
        },
        submitHandler : function(form) {
			// post
    		$.post(base_url + "/accountinfo/update", $("#updateModal .form").serialize(), function(data, status) {
    			if (data.code == "200") {
					$('#updateModal').modal('hide');
					setTimeout(function () {
						ComAlert.show(1, "更新成功", function(){
							//accountTable.fnDraw();
							window.location.href = base_url + "/accountinfo.action";
						});
					}, 315);
    			} else {
    				if (data.msg) {
    					ComAlert.show(2, data.msg);
					} else {
						ComAlert.show(2, "更新失败");
					}
    			}
    		});
		}
	});
	$("#updateModal").on('hide.bs.modal', function () {
		$("#updateModal .form")[0].reset();
	});

	// 修改密码
	$("#account_list").on('click', '.updatePassword',function() {
		// base data
		$("#updatePasswordModal .form input[name='id']").val($(this).parent().attr("id"));
		$('#updatePasswordModal').modal({backdrop: false, keyboard: false}).modal('show');
	});
	var updatePasswordModalValidate = $("#updatePasswordModal .form").validate({
		errorElement : 'span',  
        errorClass : 'help-block',
        focusInvalid : true,

		rules : {
			oldPassword : {
        		required : true
        	},
        	newPassword : {
				required : true
			},
			newPassword1 : {
				required : true,
				equalTo: "#newPassword"
			}
		},
		messages : {
			oldPassword : {
				required :"请输入旧密码."
			},
			newPassword : {
				required :"请输入新密码."
			},
			newPassword1 : {
				required : "请再次输入密码.",
				equalTo : "两次输入密码不匹配."
			}
		},
		highlight : function(element) {
            $(element).closest('.form-group').addClass('has-error');  
        },
        success : function(label) {  
            label.closest('.form-group').removeClass('has-error');  
            label.remove();  
        },
        errorPlacement : function(error, element) {  
            element.parent('div').append(error);  
        },
        submitHandler : function(form) {
			// post
    		$.post(base_url + "/accountinfo/updatePassword", $("#updatePasswordModal .form").serialize(), function(data, status) {
    			if (data.code == "200") {
					$('#updatePasswordModal').modal('hide');
					setTimeout(function () {
						ComAlert.show(1, "更新成功", function(){
							//accountTable.fnDraw();
							//window.location.href = base_url + "/accountinfo.action";
						});
					}, 315);
    			} else {
    				if (data.msg) {
    					ComAlert.show(2, data.msg);
					} else {
						ComAlert.show(2, "更新失败");
					}
    			}
    		});
		}
	});
});
